﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using SmartWallpaperChanger.Properties;

namespace SmartWallpaperChanger
{
    public class WallpaperChanger : IDisposable
    {
        private readonly WallpaperSetter setter;
        private readonly DirectoryObserver source;
        private readonly Timer changeTimer;
        private readonly Updater updater;


        public WallpaperChanger()
        {
            try
            {
                setter = new WallpaperSetter();
                source = new DirectoryObserver();
                
                updater = new Updater();
                updater.UpdateAvailable += delegate { Updater.Update(); };
                updater.StartPeriodicChecking();

                changeTimer = new Timer();
                changeTimer.Interval = (int)Settings.Default.ChangeInterval.TotalSeconds * 1000;
                changeTimer.Tick += changeTimer_Tick;
                changeTimer.Start();

                changeTimer_Tick(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler beim Initialisieren: " + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// Forces the changer to choose a new wallpaper.
        /// </summary>
        public void ForceChange()
        {
            changeTimer.Stop();
            changeTimer_Tick(this, new EventArgs());
            changeTimer.Start();
        }

        /// <summary>
        /// Changes the wallpaper to a new one.
        /// </summary>
        private void changeTimer_Tick(object sender, EventArgs e)
        {
            if (source.Wallpapers.Count > 0)
            {
                try
                {
                    string wallpaper = source.Wallpapers.GetRandomWallpaper();
                    
                    if (!string.IsNullOrEmpty(wallpaper))
                    {
                        setter.SetWallpaper(wallpaper);
                    }
                }
                catch (InvalidOperationException oEx)
                {
                    Exception ex = oEx;
                    while (ex != null)
                    {
                        MessageBox.Show(string.Format("Fehler beim Setzen des Hintergrundes: {0}", ex.Message));
                        ex = ex.InnerException;
                    }
                    throw;
                }
            }
        }

        public void Dispose()
        {
            changeTimer.Dispose();
            source.Dispose();
        }
    }
}
